
const argv = require('yargs').argv
const path = require('path')
const fs = require('fs')
if (!argv.baseUrl || !argv.distUrl) {
  throw new Error('baseUrl && distUrl is needed!')
}
const webpackRaw = require('webpack/lib/webpack')
const webpackWeb = require('webpack/lib/webpack.web')
const webpackWebLocal = require('./config/webpack.web')

const NodeOutputFileSystem = require("webpack/lib/node/NodeOutputFileSystem")
const NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem")
const CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem")

const InputFileSystemAdapter = require('./config/web/InputFileSystemAdapter')
const OutputFileSystemAdapter = require('./config/web/OutputFileSystemAdapter')

// 插件
const WebpackHandlerPlugin = require('hap-toolkit/tools/packager/webpack/plugin/handler-plugin')
const WebpackResourcePlugin = require('hap-toolkit/tools/packager/webpack/plugin/resource-plugin')
const WebpackZipPlugin = require('hap-toolkit/tools/packager/webpack/plugin/zip-plugin')

// 打包配置项
const FILE_EXT_LIST = ['.ux']
const moduleName = 'hap-toolkit'

// 文件系统
const projectUtil = require('./config/project.config')

// 1. 读取测试文件
const webpackTestData = projectUtil.readTestDataAsRoot(argv.baseUrl)
// 2. 映射到内存文件系统
const webpackFileData = projectUtil.initProjectData(webpackTestData)
// 3. 生成webpack配置
const webpackConfData = projectUtil.packProjectOptions(webpackFileData)

// TODO 设置为全局
process.webpackFileData = webpackFileData

const options = {
  entry: webpackConfData.entry,
  output: webpackConfData.output,
  module: {
    rules: [
      {
        test: new RegExp('(' + FILE_EXT_LIST.map(k => '\\' + k).join('|') + ')(\\?[^?]+)?$'),
        use: [
          path.resolve('node_modules/hap-toolkit/tools/packager/webpack/loader/ux-loader.js')
        ],
        // Disable Babel compact option
        exclude: /node_modules/
      },
      {
        test: /\.js/,
        use: [
          path.resolve('node_modules/hap-toolkit/tools/packager/webpack/loader/module-loader.js'),
          {
            loader: path.resolve('node_modules/babel-loader'),
            options: {
              babelrc: false
            }
          }
        ],
        exclude: function (path) {
          return /node_modules/.test(path) && !(new RegExp(moduleName).test(path))
        }
      }
    ]
  },
  resolve: {
    modules: [
      'node_modules'
    ],
    extensions: ['.webpack.js', '.web.js', '.js', '.json'].concat(FILE_EXT_LIST)
  },

  plugins: [
    new WebpackHandlerPlugin(),
    new WebpackResourcePlugin({
      pathSrc: webpackConfData.pathSrc,
      pathBuild: webpackConfData.pathBuild,
      sign: 'debug'
    }),
    new WebpackZipPlugin({
      name: webpackConfData.manifestPack,
      versionCode: 1001,
      output: webpackConfData.pathDist,
      pathBuild: webpackConfData.pathBuild,
      sign: 'debug',
      outputFS: webpackFileData
    })
  ],

  // 用于web的文件系统
  inputFileSystem: new CachedInputFileSystem(
    new InputFileSystemAdapter(webpackFileData),
    60000
  ),
  outputFileSystem: new OutputFileSystemAdapter(),

  // Mem
  context: webpackConfData.context
}

const compiler = webpackWebLocal(options)

compiler.run(function (err, stat) {
  if (err) {
    throw err
  }

  if (stat.compilation && stat.compilation.errors) {
    stat.compilation.errors.forEach(function (err) {
      console.info(err)
      throw new Error(err)
    })
  }

  console.info('Done!')

  // 写入NodeJS文件系统中
  const memoPathDist = projectUtil.pathMemoRoot + '/dist/'
  const rpkName = projectUtil.rpkName
  const rpkCont = process.webpackFileData.readFileSync(memoPathDist + rpkName)
  // 创建目录
  !fs.existsSync(argv.distUrl) && fs.mkdirSync(argv.distUrl)
  // 写入文件
  fs.writeFileSync(argv.distUrl + '/' + rpkName, rpkCont)
  console.info('成功生成文件:' + rpkName)
})

